package br.edu.universo.si.projeto2.infojob.client.componentes;

import com.google.gwt.user.client.ui.KeyboardListener;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;

/**
 * COMPONENTE - campo que aceita apenas numeros
 * @author Andrey A. de Oliveira
 * @since 06/09/2008 
 */
public class NumberBox extends TextBox
{
	public NumberBox(int tamanho)
	{
		super();
		this.setWidth(tamanho + "px"); // seta o tamanho do campo
		this.setTextAlignment(ALIGN_RIGHT);
		inserirFiltro();
	}

	public NumberBox()
	{
		super();
		inserirFiltro();
	}

	private void inserirFiltro()
	{
		this.addKeyboardListener(
				new KeyboardListener()
				{
					public void onKeyDown(Widget sender, char keyCode, int modifiers)
					{
						if (keyCode != '0' && keyCode != '1' && keyCode != '2' && keyCode != '3' && keyCode != '4' && 
							keyCode != '5' && keyCode != '6' && keyCode != '7' && keyCode != '8' && keyCode != '9' &&
							((int) keyCode) != KEY_BACKSPACE && ((int) keyCode) != KEY_DELETE && ((int) keyCode) != KEY_HOME && ((int) keyCode) != KEY_END 
							&& ((int) keyCode) != KEY_TAB && ((int) keyCode) != KEY_LEFT && ((int) keyCode) != KEY_RIGHT && ((int) keyCode) != KEY_SHIFT)
						{
							((TextBox) sender).cancelKey();
						}
					}

					// implementacao vazia...
					public void onKeyPress(Widget sender, char keyCode, int modifiers) { };
					public void onKeyUp(Widget sender, char keyCode, int modifiers) { };
				}
			);
		
	}

	/**
	 * Verifica se um caracter esta contido em um array de caracteres
	 * @param keys[] = array de caracteres
	 * @param keyCode = caracter
	 */
	@SuppressWarnings("unused")
	private boolean contains(char keys[], char keyCode)
	{
		for (char key : keys)
		{
			if (key == keyCode)
			{
				return true;
			}
		}

		return false;
	}
}